import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

class SpotifyPlugin_t {
  static const MethodChannel _channel = MethodChannel('spotify_plugin_t');

  /**
   * EventChannel，用于原生给flutter传值
   */
  static const EventChannel _eventChannel = EventChannel(
      "spotify_plugin_t_eventChannel");

  /**
   * 接口，配合EventChannel _eventChannel： 用于原生给flutter传值，面向接口编程
   */
  static late SpotifyPluginCallBack? _callBack;

  /**
   * 初始化接口
   */
  static ycSetPluginCallBack(SpotifyPluginCallBack value) {
    _callBack = value;
  }

  static void ycRemovePluginCallBack() {
    _callBack = null;
  }

  /**
   * 初始化这个sdk SpotifyPlugin_t.init
   */
  static init() {
    eventChannel();
  }

  /**
   * EventChannel，监听原生的调用
   */
  static eventChannel() {
    _eventChannel.receiveBroadcastStream().listen((data) {
      if (kDebugMode) {
        print("spotify eventChannel data = ${data}");
      }
      String type = data["type"];
      switch (type) {
        case "token":
          _callBack?.getIOSToken(data["accessToken"], data["refreshToken"]);
          break;
        case "goBack":
          _callBack?.callBackGoBack();
          break;
        default:
          print("SpotifyPlugin_t eventChannel listen = ${data}");
      }
    });
  }

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  /**
   * scope:以英文逗号,作为分隔符
   */
  static Future<String?> getSpotifyCode(
      {required String clientId, required String url, required String scope}) async {
    return (await _channel.invokeMethod<String?>("getSpotifyCode",
        {"clientId": clientId, "url": url, "scope": scope})) ?? "";
  }

  /**
   * scope:以英文逗号,作为分隔符
   */
  static Future<String?> getSpotifyToken(
      {required String clientId, required String url, required String scope}) async {
    return (await _channel.invokeMethod<String?>("getSpotifyToken",
        {"clientId": clientId, "url": url, "scope": scope})) ?? "";
  }

  /**
   * scope:以英文逗号,作为分隔符
   */
  static Future<Map<String, dynamic>?> getTokenByCode(String url) async {
    // return await _channel.invokeMethod("getTokenByCode",{"url":url});
    return await _channel.invokeMapMethod<String, dynamic>(
        "getTokenByCode", {"url": url});
  }
}


/**
 * 抽象类
 */
abstract class SpotifyPluginCallBack {

  void callBackUrl(String url) {}

  void callBackGoBack() {}

  void getIOSToken(String token, String refreshToken) {}
}

mixin SpotifyPluginBaseCallBack implements SpotifyPluginCallBack {
  @override
  void callBackGoBack() {
    // TODO: implement callBackGoBack
  }

  @override
  void callBackUrl(String url) {
    // TODO: implement callBackUrl
  }

  @override
  void getIOSToken(String token, String refreshToken) {
    // TODO: implement getIOSToken
  }

}